<?php
/**
 * Created by PhpStorm.
 * Script Name: ReleaseMessageHandler.php
 * Create: 2020/4/15 10:48
 * Description: 全网发布事件消息处理器
 * Author: fudaoji<fdj@kuryun.cn>
 */
namespace plugin\wechat\app\platform\handler\platform;

use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Text;
use plugin\wechat\app\service\Mp as MpService;
use plugin\wechat\app\service\OpenPlatform as OpenPlatformService;

class ReleaseMessageHandler implements EventHandlerInterface
{

    /**
     * 全网发布处理器
     * @param null $payload
     * @return Text
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author fudaoji<fdj@kuryun.cn>
     */
    public function handle($payload = null) {
        dao_log()->error('release::' . json_encode($payload, JSON_UNESCAPED_UNICODE));
        $message = $payload;
        switch($message['MsgType']) {
            case "event":
                //全网发布检测2: 事件消息   //这个貌似废弃了
                return new Text($message['Event'] . 'from_callback');
                break;
            case "text":
                //全网发布检测1: 文本检测
                $content = $message['Content'];
                if($content == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
                    return new Text('TESTCOMPONENT_MSG_TYPE_TEXT_callback');
                } elseif(strpos($content, 'QUERY_AUTH_CODE:') !== false) {
                    try {
                        $open_platform = OpenPlatformService::getOpenPlatform();
                        //全网发布检测3: API验证
                        $query_auth_code = explode(":", $content)[1];
                        //使用授权码换取公众号的授权信息
                        $handleAuthorize = $open_platform->handleAuthorize($query_auth_code);
                        $appId = $handleAuthorize['authorization_info']['authorizer_appid'];
                        // 获取授权方的帐号基本信息,主要目的是更新微信测试号的refresh_token
                        $authorizer_info = $open_platform->getAuthorizer($appId);
                        MpService::updateAuthInfo($authorizer_info);
                        $app = MpService::getApp(MpService::getInfo($appId), request());
                        //接受微信放发来的query_auth_code
                        $response = $query_auth_code . '_from_api';
                        $text = new Text($response);
                        $res = $app->customer_service->message($text)->to($message['FromUserName'])->send();
                        if(!empty($res['errcode'])){
                            dao_log()->error('全网接入检测3错误：' . OpenPlatformService::errors($res['errcode'], $res['errmsg']));
                        }
                    }catch (\Exception $e){
                        dao_log()->error('全网接入检测异常:' . json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE));
                    }
                }
                break;
        }
    }
}